package com.ys.controller.api.administration;

import com.ys.entity.administration.AdmSignetManage;
import com.ys.entity.sys.YsCol;
import com.ys.entity.sys.YsDict;
import com.ys.service.administration.AdmSignetManageService;
import com.ys.service.sys.CommonApiService;
import com.ys.service.sys.UploadService.UploadDto;
import com.ys.util.ExportExcelUtils;
import com.ys.vo.LayuiTableVoJA;
import com.ys.vo.R;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;
import java.util.Map;
import java.util.function.Predicate;
import java.util.stream.Collectors;

@Controller
@RequestMapping("/api/inter/admSignetManage")
public class ApiInterAdmSignetManageController {
    private static final Logger logger = LoggerFactory.getLogger(ApiInterAdmSignetManageController.class);
    private static Long MENU_ID = 10165L;

    @Autowired
    private CommonApiService<AdmSignetManage> commonApiService;
    @Autowired
    private AdmSignetManageService admSignetManageService;

    /**
     * 设置查询的cond的sql设置
     * @param cond
     * @return
     */
    public AdmSignetManage setSeachSql(AdmSignetManage cond){
        //cond.addField("CASE WHEN A.ExamineStatus = 1 THEN '有误' ELSE '无误' END examineStatusHtml ");
        //排序
        cond.setOrderby("A.UpdateTime DESC");
        return  cond;
    }


    /**
     * 查询
     */
    @RequiresPermissions("admSignetManage:view")
    @RequestMapping("/search")
    @ResponseBody
    public LayuiTableVoJA search(Model model, HttpServletRequest request, HttpServletResponse response,
                                 @ModelAttribute AdmSignetManage cond
    ){
        try {
            cond = setSeachSql(cond);
            LayuiTableVoJA tableVoJA = commonApiService.searchLay(cond);
            return tableVoJA;
        }catch (Exception e){
            logger.error("查询印章管理表出错：",e.getMessage(),e);
            LayuiTableVoJA tableVoJA = new LayuiTableVoJA();
            tableVoJA.setCode(1);
            tableVoJA.setMsg("查询出错，请稍后重试！");
            return tableVoJA;
        }
    }


    /**
     * 导出
     */
    @RequestMapping("/export")
    @ResponseBody
    public R export(@ModelAttribute AdmSignetManage cond){
        try {
            cond.setPage(0).setSize(999999);
            cond = setSeachSql(cond);
            //获取菜单字段数据
            List<YsCol> listField = new YsCol()
                    .setMenuId(MENU_ID)
                    .where("A.Code != 'ope'")
                    .setOrderby("A.SortNo asc")
                    .queryList();
            //获取数据
            List<Map<String, Object>> listData = cond.queryMap();
            //处理数据
            ExportExcelUtils<AdmSignetManage> util = new ExportExcelUtils<>(new AdmSignetManage());
            String toFilePath = util.exportExcel(listData, listField, "印章管理表");
            UploadDto dto = commonApiService.uploadLocalToServer(toFilePath);
            return R.ok(dto.getUrl());
        }catch (Exception e){
            logger.error("导出印章管理表出错：",e.getMessage(),e);
            return R.error("导出失败，请稍后重试！");
        }
    }



    /**
     * 新增
     */
    @RequiresPermissions("admSignetManage:add")
    @RequestMapping("/toAdd")
    @ResponseBody
    public R toAdd(HttpServletRequest request, @RequestParam Map<String, Object> params){
        try {
            String errorMsg = checkParams(params);
            if(errorMsg!=null && !"".equals(errorMsg)){
                return R.error(errorMsg);
            }
            return admSignetManageService.add(params);
        } catch (Exception e) {
            logger.error("新增印章管理表出错：",e.getMessage(),e);
            return R.error("系统正在开小差，请联系客服，我们将第一时间为您解决！");
        }
    }


    /**
     * 修改
     */
    @RequiresPermissions("admSignetManage:edit")
    @RequestMapping("/toEdit")
    @ResponseBody
    public R toEdit(HttpServletRequest request, @RequestParam Map<String, Object> params){
        try {
            String errorMsg = checkParams(params);
            if(errorMsg!=null && !"".equals(errorMsg)){
                return R.error(errorMsg);
            }
            return admSignetManageService.update(params);
        } catch (Exception e) {
            logger.error("修改印章管理表出错：",e.getMessage(),e);
            return R.error("系统正在开小差，请联系客服，我们将第一时间为您解决！");
        }
    }

    /**
     * 参数验证
     */
    public String checkParams(Map<String, Object> params){
        Predicate<String> isNotNull = item-> item!=null && !"".equals(item.trim());//是否为空，返回：非空true，空false
        String backMsg = "";
        if(params==null){
            return "参数为空！";
        }
        if(!isNotNull.test(params.get("signetName")+"")){
            return "印章名称为空！";
        }
        if(!isNotNull.test(params.get("signetType")+"")){
            return "请选择印章类型！";
        }
        if(!isNotNull.test(params.get("signetStatus")+"")){
            return "请选择印章状态！";
        }
        if(params.get("signetName").toString().length()>20){
            return "印章名称的长度不要大于20！";
        }
        List<YsDict> dictList = new YsDict().where("A.DictKey IN ('signet_type','signet_status')").queryList();
        List<YsDict> dictListByType = dictList.stream().filter(item->item.getDictKey().equals("signet_type")).collect(Collectors.toList());
        if(dictListByType.size()>0){
            boolean isSame = false;
            for (YsDict item :dictListByType){
                if(item.getDictValue().equals(params.get("signetType").toString())) isSame=true;
            }
            if(!isSame){
                return "未知的印章类型！";
            }
        }
        List<YsDict> dictListByStatus = dictList.stream().filter(item->item.getDictKey().equals("signet_status")).collect(Collectors.toList());
        if(dictListByStatus.size()>0){
            boolean isSame = false;
            for (YsDict item :dictListByStatus){
                if(item.getDictValue().equals(params.get("signetStatus").toString())) isSame=true;
            }
            if(!isSame){
                return "未知的印章状态！";
            }
        }
        return backMsg;

    }



    /**
     * 删除
     */
    @RequestMapping("/del")
    @ResponseBody
    public R del(HttpServletRequest request, Long id){
        try {
            admSignetManageService.del(id);
            return R.ok();
        } catch (Exception e) {
            logger.error("删除印章管理表出错：",e.getMessage(),e);
            return R.error("系统正在开小差，请联系客服，我们将第一时间为您解决！");
        }
    }


    @RequestMapping("/searchSignetManage")
    @ResponseBody
    public LayuiTableVoJA searchSignetManage(Model model, HttpServletRequest request, HttpServletResponse response,
                                 @ModelAttribute AdmSignetManage cond
    ){
        try {
            cond.addField("A.Code AS signetCode");
            cond.addField("CASE WHEN U.Bid IS NULL THEN '0' ELSE '1' END isUsed ");
            cond.addField("CASE WHEN U.Bid IS NULL THEN '未借出' ELSE '已借出' END isUsedTxt ");
            //（0公章，1财务章，2合同章，3法人章，4私章，5其他）
            cond.addField("CASE WHEN A.SignetType=0 THEN '公章' WHEN A.SignetType=1 THEN '财务章' " +
                    "WHEN A.SignetType=2 THEN '合同章' WHEN A.SignetType=3 THEN '法人章' " +
                    "WHEN A.SignetType=4 THEN '私章' ELSE '其他' END signetTypeTxt ");
            cond.addLeftJoin("ADM_UseSignetApply U ON A.Code = U.SignetCode AND U.EffectStock = 0 AND U.Purpose = 0 ");
            cond.setSignetStatus(1);
            cond.setOrderby("A.Code ASC");

            LayuiTableVoJA tableVoJA = commonApiService.searchLay(cond);
            return tableVoJA;
        }catch (Exception e){
            logger.error("查询印章管理表出错：",e.getMessage(),e);
            LayuiTableVoJA tableVoJA = new LayuiTableVoJA();
            tableVoJA.setCode(1);
            tableVoJA.setMsg("查询出错，请稍后重试！");
            return tableVoJA;
        }
    }

}